package biz

import (
	"fmt"
	"github.com/heroiclabs/nakama-common/runtime"
)

type ErrorCode int

const (
	ErrUnmarshalPayload ErrorCode = 13
	ErrMarshalPayload   ErrorCode = 14
	ErrNotFoundRoom     ErrorCode = 15
	ErrMissRoomCode     ErrorCode = 16
	ErrInvalidRoomCode  ErrorCode = 17
	ErrInvalidArgument  ErrorCode = 3
	ErrNotFound         ErrorCode = 5

	ErrUnknown ErrorCode = 1000
	// 其他错误码...
)

var errorMessages = map[ErrorCode]string{
	ErrUnmarshalPayload: "unable to unmarshal payload",
	ErrMarshalPayload:   "unable to marshal payload",
	ErrNotFoundRoom:     "room not found",
	ErrMissRoomCode:     "missing room_code",
	ErrInvalidRoomCode:  "invalid room_code type",
	ErrInvalidArgument:  "invalid argument",
	ErrNotFound:         "not found",
	ErrUnknown:          "unknown",
	// 继续补充
}

func (e ErrorCode) Error() string {
	if msg, ok := errorMessages[e]; ok {
		return msg
	}
	return "unknown error"
}

// NewError 支持包装原始 error 的版本
func NewError(code ErrorCode, cause error) error {
	msg, ok := errorMessages[code]
	if !ok {
		msg = "unknown error"
	}
	if cause != nil {
		msg = fmt.Sprintf("%s: %v", msg, cause)
	}
	return runtime.NewError(msg, int(code))
}
